//
//  HRPostSoundViewController.m
//  Hear
//
//  Created by mac on 2017/4/10.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRPostSoundViewController.h"
#import "PlaceholderTextView.h"
#import <TPKeyboardAvoidingScrollView.h>
//#import "MyPlayTool.h"
#import "OSSImageUploader.h"
#import "HRDynamicModel.h"
#import "HRPostDynamicViewModel.h"

#import "HRMessageToolBar.h"
#import "HRTagViewController.h"
#import "HRDynamicRootViewController.h"
#import "HRCircleOfFirendsViewController.h"
#import "HRDynamicViewController.h"
@interface HRPostSoundViewController ()<UITextViewDelegate>{
    float noteTextHeight;
    float allViewHeight;
}
@property (nonatomic, strong)TPKeyboardAvoidingScrollView *scrollView;
@property(nonatomic,strong) PlaceholderTextView *noteTextView;
@property(nonatomic,strong) UILabel *textNumberLabel;
@property(nonatomic,strong) UIButton *submitBtn;
@property (nonatomic, strong)UIButton *permissionButton;
@property (nonatomic, strong)UIButton *playButton;
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;


@property(nonatomic, strong)HRMessageToolBar *chatToolbar;
@property(strong, nonatomic) EaseFaceView *faceView;

@property (weak, nonatomic) id<EaseMessageViewControllerDataSource> dataSource;
@property (weak, nonatomic) id<EaseMessageViewControllerDelegate> delegate;
@property(nonatomic, assign)BOOL isOpen;


@property(nonatomic, assign)NSInteger index;
@property(nonatomic, strong)UIButton *tagButton;

@property(nonatomic,strong) UILabel *explainLabel;

@end

@implementation HRPostSoundViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initViews];
    
}


- (void)initViews{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"瞬间";
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:0];
//    [leftButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    UIButton *submitBtn = [[UIButton alloc]init];
    submitBtn.size = CGSizeMake(60, 30);
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.submitBtn = submitBtn;
    
    //收起键盘
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    [self.view addGestureRecognizer:tapGr];
    
    
    self.scrollView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.scrollView];
    
    
    self.LQPhotoPicker_superView = _scrollView;
    
    self.LQPhotoPicker_imgMaxCount = 1;
    
    [self LQPhotoPicker_initPickerView];
    
    self.LQPhotoPicker_delegate = self;
    
    
    [self setuoView];
    
    //    [_scrollView addSubview:(self.permissionButton = permissionButton)];
//    [_scrollView addSubview:(self.playButton = playButton)];
//    [_scrollView addSubview:_submitBtn];
    
    

    
    
    
    
    self.chatToolbar = [[HRMessageToolBar alloc] initWithFrame:CGRectMake(0, kFullHeight- 50-kBottomHeight, kFullWidth, 50+kBottomHeight) keyboardType:DXKeyboardTypeNoTextViewInput];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    
    
    [self setupEmotion];
    
    self.index = self.MomentTagCode.length > 0?[self.MomentTagCode intValue]:1;
    
}


- (void)setuoView{
    _noteTextView = [[PlaceholderTextView alloc]init];
    _noteTextView.textColor = TEXTCOLOR;
    _noteTextView.delegate = self;
    _noteTextView.font = CustomUIFont(14);
    _noteTextView.placeholder = @"说点什么";
    
    _textNumberLabel = [[UILabel alloc]init];
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    _textNumberLabel.font = [UIFont boldSystemFontOfSize:12];
    _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    _textNumberLabel.backgroundColor = [UIColor whiteColor];
    _textNumberLabel.text = @"0/1000    ";
    
    
    
    _explainLabel = [[UILabel alloc]init];
    _explainLabel.text = @"可以选择一张图片作为语音封面";
    _explainLabel.textColor = [UIColor colorWithRed:199.0/255.0 green:199.0/255.0 blue:199.0/255.0 alpha:1.0];
    _explainLabel.textAlignment = NSTextAlignmentCenter;
    _explainLabel.font = [UIFont boldSystemFontOfSize:12];
    
    
    
    self.tagButton = [UIButton buttonWithType:0];
    [self.tagButton setTitle:self.MomentTagName.length > 0?[NSString stringWithFormat:@" %@",self.MomentTagName]:@" 我的心情日记" forState:0];
    [self.tagButton setImage:[UIImage imageNamed:@"标签icon-拷贝"] forState:0];
    [self.tagButton setTitleColor:MainColor forState:0];
    self.tagButton.titleLabel.font = CustomUIFont(12);
    [self.tagButton addTarget:self action:@selector(didSelectTag) forControlEvents:UIControlEventTouchUpInside];
    
    [_scrollView addSubview:_explainLabel];

    [_scrollView addSubview:_noteTextView];
    [_scrollView addSubview:_textNumberLabel];
    [_scrollView addSubview:self.tagButton];

    
    [self updateViewsFrame];


}


#pragma 提交数据
-(void)submitBtnClicked{
    
    _submitBtn.enabled = NO;
    [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];
    
    if (self.noteTextView.text.length > 1000){
        [MBProgressHUD showMessage:@"文字描述不超过1000长度" finishBlock:nil];
        return;
    }
    
    
    [OSSImageUploader asyncUploadSound:@[self.outPutFilePath] complete:^(NSArray<NSString *> *names, UploadImageState state) {

        if (state == UploadImageFailed) return ;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.LQPhotoPicker_selectedAssetArray.count){// 有图片 为图片语音贴
                [self postImageData:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]]];
            }else{
                _submitBtn.enabled = YES;

                [self postDynamic:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] andImageJson:@""];
            }
        });
        
    }];
    
    
}




- (void)postImageData:(NSString *)soundUrl{
    [OSSImageUploader asyncUploadImages:self.LQPhotoPicker_selectedAssetArray complete:^(NSArray<NSString *> *names, UploadImageState state) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _submitBtn.enabled = YES;
        });
        
        
        if (state == UploadImageFailed) return ;
        
        NSMutableArray *formatImageArr = [NSMutableArray array];
        for (NSString *url in names)
        {
            [formatImageArr addObject:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,url]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *error = nil;
            NSString *imageJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:formatImageArr options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];
            
            
            [self postDynamic:soundUrl andImageJson:imageJson];
        });
    }];
}



- (void)postDynamic:(NSString *)soundUrl andImageJson:(NSString *)imageJson{
    
    [MBProgressHUD hideHUDForView:WINDOW animated:YES];

    
    HRPostDynamicRequestModel *requestModel = [HRPostDynamicRequestModel new];
    
    
    if (imageJson.length){
        requestModel.MomentType = @"5";

        
        NSMutableDictionary *detaiDict = [NSMutableDictionary dictionary];
        detaiDict[@"SoundUrl"] = soundUrl;
        detaiDict[@"PhotoUrl"] = imageJson;
        detaiDict[@"SoundLength"] = self.timeLabel;
        
        NSError *error = nil;

        NSString *MomentDetaiJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:detaiDict options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];

        requestModel.MomentDetai = MomentDetaiJson;

    }else{
        requestModel.MomentType = @"1";

        requestModel.MomentDetai = soundUrl;

    }
    
    
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    

    requestModel.MomentNotes = self.noteTextView.text;
    if (!self.noteTextView.text.length){
        requestModel.MomentNotes = @"";
    }
    requestModel.PositionName = ADDRESS;
    requestModel.MomentLength = self.timeLabel;
    requestModel.VideoCover = @"";

    NSString *Longitude = @"0";
    if ([LONGITUDE length]){
        Longitude = LONGITUDE;
    }
    
    NSString *Latitude = @"0";
    if ([LATITUDE length]){
        Latitude = LATITUDE;
    }
    requestModel.Longitude = Longitude;
    requestModel.Latitude = Latitude;
    if (self.isOpen){
        requestModel.Permission = 0;
    }else{
        requestModel.Permission = 1;
    }
    requestModel.CreateTime = [self getCurrentTime];
    
    requestModel.MomentTagCode = [NSString stringWithFormat:@"%ld",(long)self.index];
    requestModel.MomentTagName = [self.tagButton.titleLabel.text substringFromIndex:1];

    WeakSelf
    [[HRPostDynamicViewModel  new] postDynamicRequstModel:requestModel isSeccess:^(HRDynamicModel *dynamicModel) {
        if (dynamicModel){
            [MBProgressHUD showMessage:@"发布成功" finishBlock:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.isSound){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadMyDynaminclist" object:nil];

                    for (UIViewController *controller in self.navigationController.viewControllers) {
                        if (self.isFromMine){
                            if ([controller isKindOfClass:[HRDynamicViewController class]]) {
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }else{
                            if ([controller isKindOfClass:[HRCircleOfFirendsViewController class]]) {
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                        
                    }
                }
            });
        }
    }];

}

- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}





- (void)playButtonClick{
    if (self.playButton.selected){
        self.playButton.selected = NO;
//        [self stopTransformAnimation];
        [self stopPlaying];
    }else{
        self.playButton.selected = YES;
//        [self startTransformAnimation];
        [self playRecordingWithPath:self.outPutFilePath];
    }
}

- (void)startTransformAnimation
{
    
    CFTimeInterval pausedTime = [self.playButton.layer
                                 timeOffset];
    self.playButton.layer.speed = 1.0;
    self.playButton.layer.timeOffset = 0.0;
    
    self.playButton.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self.playButton.layer
                                     convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.playButton.layer.beginTime = timeSincePause;
    
    
}
- (void)stopTransformAnimation
{
    CFTimeInterval pausedTime = [self.playButton.layer
                                 convertTime:CACurrentMediaTime() fromLayer:nil];
    self.playButton.layer.speed = 0.0;
    
    self.playButton.layer.timeOffset = pausedTime;
    
    
}


- (void)updateViewsFrame{
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 100;
    }
    
    _noteTextView.frame = CGRectMake(15, 0, kFullWidth - 30, noteTextHeight);

    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15, kFullWidth-10, 15);

    
//    _permissionButton.frame = CGRectMake(self.view.width-100, _textNumberLabel.top, 20, 20);

    [self LQPhotoPicker_updatePickerViewFrameY:_textNumberLabel.frame.origin.y + _textNumberLabel.frame.size.height];

    

    
    _playButton.frame = CGRectMake(20, _textNumberLabel.top, 30, 30);
    
//    _submitBtn.frame = CGRectMake(20, _textNumberLabel.frame.origin.y+_textNumberLabel.frame.size.height +50, kFullWidth -40, 45);
    allViewHeight = noteTextHeight + [self LQPhotoPicker_getPickerViewFrame].size.height + 30 + 100;

    
    _explainLabel.frame = CGRectMake(0, [self LQPhotoPicker_getPickerViewFrame].origin.y+[self LQPhotoPicker_getPickerViewFrame].size.height+10, kFullWidth, 20);
    self.tagButton.width = [self.tagButton.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}].width+15;

    
    self.tagButton.frame = CGRectMake(15, _explainLabel.bottom+15, 110, 20);


    _scrollView.contentSize = self.scrollView.contentSize = CGSizeMake(0,allViewHeight+30);

}



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/1000    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 1000) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    
    [self textChanged];
    
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//    }
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/1000    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 1000) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
}

-(void)textChanged{
    
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }
    [self updateViewsFrame];
}

- (void)permissionButtonClick{
    if (self.permissionButton.selected){
        [self.permissionButton setImage:[UIImage imageNamed:@"开锁"] forState:0];
        self.permissionButton.selected = NO;
    }else{
        [self.permissionButton setImage:[UIImage imageNamed:@"闭锁"] forState:0];
        self.permissionButton.selected = YES;
    }
}

- (void)viewTapped{
    [self.view endEditing:NO];
    [self.chatToolbar endEditing:YES];

}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)playRecordingWithPath:(NSString *)RecordPath{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    NSURL *url;
    url = [NSURL fileURLWithPath:RecordPath];
    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
    if (error != nil){
        [self stopPlaying];
    }else{
        self.audioPlayer.numberOfLoops = 0;
        self.audioPlayer.delegate = self;
        [self.audioPlayer play];
        DDLog(@"playing");
    }
}

-(void)stopPlaying
{
    
    DDLog(@"stopPlaying");
    [self.audioPlayer stop];
    self.audioPlayer = nil;
}


/*!
 @method
 @brief 设置表情
 @discussion 加载默认表情，如果子类实现了dataSource的自定义表情回调，同时会加载自定义表情
 @result
 */
- (void)setupEmotion
{
    if ([self.dataSource respondsToSelector:@selector(emotionFormessageViewController:)]) {
        NSArray* emotionManagers = [self.dataSource emotionFormessageViewController:self];
        [self.faceView setEmotionManagers:emotionManagers];
    } else {
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSString *name in [EaseEmoji allEmoji]) {
            EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
            [emotions addObject:emotion];
        }
        EaseEmotion *emotion = [emotions objectAtIndex:0];
        EaseEmotionManager *manager= [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:emotion.emotionId]];
        [self.faceView setEmotionManagers:@[manager]];
    }
}


- (void)setChatToolbar:(HRMessageToolBar *)chatToolbar
{
    [_chatToolbar removeFromSuperview];
    
    _chatToolbar = chatToolbar;
    if (_chatToolbar) {
        [self.view addSubview:_chatToolbar];
    }
    
    if ([chatToolbar isKindOfClass:[HRMessageToolBar class]]) {
        [(HRMessageToolBar *)self.chatToolbar setDelegate:self];
        //        self.chatBarMoreView = (EaseChatBarMoreView*)[(HRMessageToolBar *)self.chatToolbar moreView];
        self.faceView = (EaseFaceView*)[(HRMessageToolBar *)self.chatToolbar faceView];
        self.faceView.delegate = self;
    }
}


- (void)setDataSource:(id<EaseMessageViewControllerDataSource>)dataSource
{
    //    _dataSource = dataSource;
    
    [self setupEmotion];
}

#pragma mark EMFaceDelegate
- (void)selectedFacialView:(NSString *)str isDelete:(BOOL)isDelete{
    NSString *chatText = self.noteTextView.text;
    
    if (!isDelete && str.length > 0) {
        self.noteTextView.text = [NSString stringWithFormat:@"%@%@",chatText,str];
    }
}

#pragma mark 选择标签
- (void)didSelectTag{
    
    [self.view endEditing:NO];

    
    HRTagViewController *tagVC = [HRTagViewController new];
    WeakSelf
    tagVC.selectTagNameBlock = ^(NSString *tagName, NSString *tagId) {
        [weakSelf.tagButton setTitle:[NSString stringWithFormat:@" %@",tagName] forState:0];
        weakSelf.tagButton.width = [weakSelf.tagButton.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}].width+15;
        weakSelf.index = [tagId integerValue];
    };
    [self.navigationController pushViewController:tagVC animated:YES];
}


-(void)didSelectOpen:(BOOL)isOpen{
    self.isOpen = isOpen;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

-(void)didSelectButton:(BOOL)isSelect{
    if (isSelect){
        [self.noteTextView resignFirstResponder];
    }else{
        [self.noteTextView becomeFirstResponder];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.chatToolbar endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
